import axios from "axios";
import nProgress from "nprogress";
import "nprogress/nprogress.css";

const requests = axios.create({
  baseURL: "/api",
  timeout: 20000,
});
// 请求拦截器
requests.interceptors.request.use(
  function (config) {
    nProgress.start();

    const token = sessionStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = "Bearer" + token;
    }
    // 4. 确保 Content-Type 默认设置（避免跨域预检问题）
    if (!config.headers["Content-Type"]) {
      config.headers["Content-Type"] = "application/json";
    }
    return config;
  },
  function (error) {
    nProgress.done();
    return Promise.reject(error);
  }
);
// 响应拦截器
requests.interceptors.response.use(
  function (response) {
    nProgress.done();

    const token =
      response.headers["Authorization"] || response.headers["authorization"];

    if (token) {
      sessionStorage.setItem("token", token);

      const strings = token.split(".");
      const userInfo = JSON.parse(
        decodeURIComponent(
          escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))
        )
      );
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    }
    return response.data;
  },
  function (error) {
    nProgress.done();

    if (error.response && error.response.status === 401) {
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
      router.push("/login");
    }
    return Promise.reject(error);
  }
);

export default requests;
